package com.jyy.prefabricated.service;

import com.alibaba.fastjson.JSON;
import com.jyy.prefabricated.dto.AnswerDto;
import com.jyy.prefabricated.entity.*;
import com.jyy.prefabricated.enums.ExerciseStatusEnum;
import com.jyy.prefabricated.enums.QuestionTypeEnum;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.mapper.*;
import com.jyy.prefabricated.utils.UserUtils;
import com.jyy.prefabricated.vo.ExamResultVo;
import com.jyy.prefabricated.vo.ExerciseQuestionOptionVo;
import com.jyy.prefabricated.vo.StudentExercisePaperVo;
import com.jyy.prefabricated.vo.StudentExerciseQuestionVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @version 1.0.0
 * @author: zjj
 */

@Service
public class StudentErrorQuestionService {

    @Resource
    private StudentErrorQuestionMapper studentErrorQuestionMapper;

    @Resource
    private StudentExerciseMapper studentExerciseMapper;

    @Resource
    private OptionMapper optionMapper;

    @Resource
    private UserUtils userUtils;

    @Resource
    private ExamPaperMapper paperMapper;
    @Resource
    private QuestionMapper questionMapper;

    /**
     * 错题回答答案
     * @param dto
     * @return
     */
    public StudentExercisePaperVo answer(AnswerDto dto){

        Student student = userUtils.getCurrentStudent();
        StudentErrorQuestion studentErrorQuestion = studentErrorQuestionMapper.selectByPrimaryKey(dto.getId());
        if(StringUtils.isNotBlank(dto.getAnswer()) && !StringUtils.isBlank(studentErrorQuestion.getAnswer())){
            //当提交答案不为空并且此题还未作答时时去保存答案
            studentErrorQuestion.setAnswer(dto.getAnswer());
            List<Option> options = optionMapper.selectByQuestionId(studentErrorQuestion.getQuestionId());
            //筛选出正确答案的选项数组
            List<Integer> ids = options.stream().filter(e-> e.getIfAnswer() != null && e.getIfAnswer() ).map(e->e.getId()).collect(Collectors.toList());
            List<Integer> submitAnswers = JSON.parseArray(dto.getAnswer(),Integer.class);
            Boolean ifRight = true;
            for(Integer optionId : ids){
                if(!submitAnswers.contains(optionId)){
                    ifRight = false;
                }
            }
            studentErrorQuestion.setIfRight(ifRight);
            update(studentErrorQuestion);
        }
        return fetchQuestionsByExamPaperIdAndStudentId(studentErrorQuestion.getExamPaperId(),student.getId());

    }

    /**
     * 更新
     * @param studentErrorQuestion
     * @return
     */
    public int update(StudentErrorQuestion studentErrorQuestion){
        if(studentErrorQuestion.getId() == null){
            throw new CustomException("参数id不能为空");
        }
        return studentErrorQuestionMapper.updateByPrimaryKeySelective(studentErrorQuestion);
    }

    /**
     * 根据练习id和学生id获取学员错题
     * @param examPaperId
     * @param studentId
     * @return
     */
    public StudentExercisePaperVo fetchQuestionsByExamPaperIdAndStudentId(Integer examPaperId,Integer studentId){
        StudentExercisePaperVo paperVo = new StudentExercisePaperVo();

        ExamPaper examPaper =  paperMapper.selectByPrimaryKey(examPaperId);

        paperVo.setTitle(examPaper.getName());

        List<StudentExerciseQuestionVo> questions = studentErrorQuestionMapper.selectQuestionVoByExamPaperIdAndStudentIdNoAnswer(examPaperId,studentId);

        for (StudentExerciseQuestionVo question : questions) {
            if (question.getQuestionType().equals(QuestionTypeEnum.SINGLE.getValue()) || question.getQuestionType().equals(QuestionTypeEnum.MULTIPLE.getValue())) {
                if (question.getAnswer() == null) {
                    question.setStudentAnswer("未答题");
                } else {
                    String ans = "";
                    List<Integer> submitAnswers = JSON.parseArray(question.getAnswer(), Integer.class);

                    for (int i = 0; i < submitAnswers.size(); i++) {
                        char emumOption = 'A';
                        for (ExerciseQuestionOptionVo option : question.getOptions()) {
                            if (option.getId().equals(submitAnswers.get(i))) {
                                ans += emumOption;
                                break;
                            }
                            emumOption = (char) (emumOption + 1);
                        }
                    }
                    question.setStudentAnswer(ans);
                }
                String standardAnswer = "";
                char emumOption = 'A';
                for (ExerciseQuestionOptionVo option : question.getOptions()) {
                    if (option.getIfAnswer()) {
                        standardAnswer += emumOption;
                    }
                    emumOption = (char) (emumOption + 1);
                }
                question.setStandardAnswer(standardAnswer);

            }
            //判断题
            else if (question.getQuestionType().equals(QuestionTypeEnum.JUDGE.getValue())) {

                List<Integer> submitAnswers = JSON.parseArray(question.getAnswer(), Integer.class);
                if (submitAnswers == null || submitAnswers.size() == 0) {
                    question.setStudentAnswer("未答题");
                } else if (submitAnswers.get(0) == 1) {
                    question.setStudentAnswer("1");
                } else {
                    question.setStudentAnswer("2");
                }
                Question qe = questionMapper.selectByPrimaryKey(question.getQuestionId());
                if (qe.getJudgmentAnswer()) {
                    question.setStandardAnswer("1");

                } else {
                    question.setStandardAnswer("2");

                }
            }


        }


        paperVo.setQuestionCount(questions.size());
        paperVo.setQuestions(questions);
        return paperVo;
    }


    /**
     * 结束错题练习
     *
     * @param examPaperId
     */
    public ExamResultVo finishErrorExercise(Integer examPaperId) {
        Student student = userUtils.getCurrentStudent();
        ExamResultVo resultVo = new ExamResultVo();
        List<StudentExerciseQuestionVo> questions = studentErrorQuestionMapper.selectQuestionVoByExamPaperIdAndStudentId(examPaperId,student.getId());
        Integer rightCount = 0;
        Integer errorCount = 0;
        Integer unAnswerCount = 0;
        Integer answerCount = 0;
        List<StudentErrorQuestion> studentErrorQuestions = new ArrayList<>();
        for (StudentExerciseQuestionVo question : questions) {
            if (question.getAnswer() == null) {
                unAnswerCount++;
            } else {
                answerCount++;
                if(question.getIfRight()!=null){
                    if (question.getIfRight()) {
                        rightCount++;
                    } else {
                        errorCount++;
                    }
                }

            }
        }
        resultVo.setUnAnswerCount(unAnswerCount);
        resultVo.setAnswerCount(answerCount);
        resultVo.setRightCount(rightCount);
        resultVo.setErrorCount(errorCount);

        //删除已做对的错题
        studentErrorQuestionMapper.deleteByStudentIdAndExamPaperId(examPaperId,student.getId());
        return resultVo;
    }
}
